<template>
  <div style="width: 100vw; height: 100%">
    <q-toolbar class="q-pl-none q-pr-none" >
      <!-- 左侧按钮区域 -->
      <div
        class="row items-center q-gutter-sm"
        style="flex-shrink: 0; display: flex; align-items: center;margin-left: 1%; "
      >
        <q-btn @click="openProjectManager" label="项目管理" color="primary" />
        <q-select
          v-model="selectedProject"
          :options="existingProjects"
          option-value="id"
          option-label="name"
          label="选择项目"
          emit-value
          map-options
          color="secondary"
          style="min-width: 10vw; margin-left: 2vw"
          @update:model-value="updateSelectedProject"
        />
      </div>

      <!-- 中间部分，确保 q-tabs 居中 -->
      <div
        class="q-toolbar-title"
        style="flex-grow: 1; display: flex; justify-content: center"
      >
        <q-tabs
          v-model="subTab"
          class="text-black"
          align="center"
          style="
            max-width: 60vw;
            margin-left: -27%;
            flex-grow: 1;
            display: flex;
            justify-content: center;
          "
        >
          <q-tab
            v-if="availableTabs.includes('modeling')"
            name="modeling"
            label="组轨迹建模"
          />
          <q-tab
            v-if="availableTabs.includes('result')"
            name="result"
            label="结果展示"
          />
          <q-tab
            v-if="availableTabs.includes('drawing')"
            name="drawing"
            label="自由绘图"
          />
        </q-tabs>
      </div>

      <!-- 右侧全屏按钮，使用绝对定位 -->
      <q-btn
        color="secondary"
        flat
        @click="$q.fullscreen.toggle()"
        :icon="$q.fullscreen.isActive ? 'fullscreen_exit' : 'fullscreen'"
        style="
          position: absolute;
          right: 0;
          top: 50%;
          transform: translateY(-50%);
        "
      >
        <q-tooltip transition-show="rotate" transition-hide="rotate">
          {{ $q.fullscreen.isActive ? "退出全屏" : "进入全屏" }}
        </q-tooltip>
      </q-btn>
    </q-toolbar>
    <div class="q-pa-md q-gutter-md">
      <!-- 始终显示 FileControl 组件，并传递 subTab 和 selectedProject -->
      <FileControl
        :selectedProject="selectedProject"
        :selectedProjectName="selectedProjectName"
        :currentTab="subTab"
        @update-tab="handleUpdateTab"
        @update-available-tabs="handleUpdateAvailableTabs"
      />
    </div>

    <!-- 项目管理对话框 -->
    <q-dialog v-model="projectManagerDialog" persistent>
      <q-card style="min-width: 350px">
        <q-card-section class="row items-center">
          <div class="text-h6">项目管理</div>
          <q-space />
          <q-btn icon="close" flat round dense v-close-popup />
        </q-card-section>

        <q-card-section>
          <!-- 创建新项目部分 -->
          <div class="row items-center q-mb-md">
            <q-input
              v-model="newProjectName"
              label="新项目名称"
              class="col"
              :rules="[val => !!val || '项目名称不能为空']"
            />
            <q-btn
              @click="handleCreateProject"
              label="创建"
              color="primary"
              class="q-ml-sm"
              :disable="!newProjectName"
            />
          </div>

          <!-- 项目列表部分 -->
          <div class="text-subtitle2 q-mb-sm">现有项目</div>
          <q-list separator>
            <q-item v-for="project in existingProjects" :key="project.id">
              <q-item-section>
                <q-item-label>{{ project.name }}</q-item-label>
              </q-item-section>
              <q-item-section side>
                <q-btn
                  flat
                  round
                  color="negative"
                  icon="delete"
                  size="sm"
                  @click="confirmDeleteProject(project)"
                >
                  <q-tooltip>删除项目</q-tooltip>
                </q-btn>
              </q-item-section>
            </q-item>
          </q-list>
        </q-card-section>
      </q-card>
    </q-dialog>

    <!-- 删除确认对话框 -->
    <q-dialog v-model="deleteConfirmDialog" persistent>
      <q-card>
        <q-card-section class="row items-center">
          <q-avatar icon="warning" color="negative" text-color="white" />
          <span class="q-ml-sm">
            确定要删除项目 "{{ projectToDelete?.name }}" 吗？此操作不可恢复。
          </span>
        </q-card-section>

        <q-card-actions align="right">
          <q-btn flat label="取消" color="primary" v-close-popup />
          <q-btn
            flat
            label="删除"
            color="negative"
            @click="handleDeleteProject"
            v-close-popup
          />
        </q-card-actions>
      </q-card>
    </q-dialog>
  </div>
</template>

<script setup>
import { createProject, getProjects, deleteProject } from "src/api/api";
import { ref, onMounted } from "vue";
import { useQuasar } from 'quasar';
import FileControl from "src/components/FileControl.vue";

const $q = useQuasar();
const projectManagerDialog = ref(false);
const deleteConfirmDialog = ref(false);
const newProjectName = ref("");
const projectToDelete = ref(null);
const subTab = ref("modeling");
const selectedProject = ref(null);
const selectedProjectName = ref("");
const existingProjects = ref([]);
const availableTabs = ref(['modeling']);

// 获取 userId
const userId = 1;

onMounted(async () => {
  // 获取项目列表，并映射到 { id, name } 对象
  const res = await getProjects(userId);
  console.log("res", res);
  if (res.data.code === 200) {
    existingProjects.value = res.data.data.map((project) => ({
      id: project.id, // 项目的 id 作为值
      name: project.name, // 项目的 name 作为显示文本
    }));
  }

  // 确保初始只显示组轨迹建模标签
  availableTabs.value = ['modeling'];
  subTab.value = 'modeling';
});

// 打开项目管理器
const openProjectManager = () => {
  projectManagerDialog.value = true;
  newProjectName.value = ""; // 清空新项目名称输入
};

// 确认删除项目
const confirmDeleteProject = (project) => {
  projectToDelete.value = project;
  deleteConfirmDialog.value = true;
};

// 处理删除项目
const handleDeleteProject = async () => {
  try {
    const res = await deleteProject(projectToDelete.value.id);
    if (res.data.code === 200) {
      // 从列表中移除被删除的项目
      existingProjects.value = existingProjects.value.filter(
        project => project.id !== projectToDelete.value.id
      );

      // 如果删除的是当前选中的项目，清空选择
      if (selectedProject.value === projectToDelete.value.id) {
        selectedProject.value = null;
        selectedProjectName.value = "";
      }

      $q.notify({
        type: 'positive',
        message: '项目已成功删除',
        position: 'top'
      });
    }
  } catch (error) {
    $q.notify({
      type: 'negative',
      message: error.message || '删除项目时发生错误',
      position: 'top'
    });
  } finally {
    projectToDelete.value = null;
  }
};

// 处理创建项目
const handleCreateProject = async () => {
  if (!newProjectName.value) return;

  try {
    const res = await createProject({
      name: newProjectName.value,
      user_id: userId,
    });

    if (res.data.code === 200) {
      const newProject = {
        id: res.data.data.id,
        name: newProjectName.value,
      };

      existingProjects.value.push(newProject);
      selectedProject.value = newProject.id;
      selectedProjectName.value = newProject.name;

      $q.notify({
        type: 'positive',
        message: '项目创建成功',
        position: 'top'
      });

      newProjectName.value = ""; // 清空输入
    }
  } catch (error) {
    $q.notify({
      type: 'negative',
      message: '创建项目失败',
      position: 'top'
    });
  }
};

function updateSelectedProject(id) {
  const selected = existingProjects.value.find((project) => project.id === id);
  selectedProject.value = selected.id;
  selectedProjectName.value = selected.name;

  // 切换项目时也重置为只显示组轨迹建模标签
  availableTabs.value = ['modeling'];
  subTab.value = 'modeling';
}

const handleUpdateTab = (newTab) => {
  subTab.value = newTab;
};

const handleUpdateAvailableTabs = (tabs) => {
  availableTabs.value = tabs;
};
</script>

<style scoped>
/* 添加项目列表样式 */
.q-list {
  max-height: 300px;
  overflow-y: auto;
}

.q-item {
  transition: background-color 0.3s;
}

.q-item:hover {
  background-color: #f5f5f5;
}

/* 美化滚动条 */
.q-list::-webkit-scrollbar {
  width: 6px;
}

.q-list::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.q-list::-webkit-scrollbar-thumb {
  background: #ccc;
  border-radius: 3px;
}

.q-list::-webkit-scrollbar-thumb:hover {
  background: #999;
}
</style>
